package cashpointer.core.actions;

import cashpointer.core.model.Address;
import cashpointer.core.model.GeoPoint;
import cashpointer.core.support.ContextStore;
import cashpointer.core.support.GeoPointFinder;
import com.opensymphony.xwork2.ActionSupport;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Akcja testujaca sprawdzenie polozenia geograficznego.
 * @author wojciech topolski
 * @version 2009-03-20
 */
public class NettestAction extends ActionSupport {
    public String execute() {
        // Pobranie contextu Springa.
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        // Pobranie contextStoreBean.
        ContextStore contextStoreBean = (ContextStore) ctx.getBean("contextStoreBean");

        // Pobranie coordinatesFinderBean.
        GeoPointFinder geoPointFinderBean = (GeoPointFinder) ctx.getBean("geoPointFinderBean");

        // Ustawiam tryb wyswietlania.
        contextStoreBean.setOutputMode(true);

        // Adres testowy.
        Address addressTest = new Address();
        addressTest.setRegion("Łódzkie");
        addressTest.setCity("Łódź");
        addressTest.setStreet("Piotrkowska 1");

        // Pobranie polozenia geograficznego.
        GeoPoint gpTest = geoPointFinderBean.findByAddress(addressTest, ctx);

        // Generowanie XML z adresu.
        XStream addressXstream = new XStream(new DomDriver());
        addressXstream.alias("address", Address.class);
        String addressXML = addressXstream.toXML(addressTest);

        if (gpTest != null && gpTest.getLatitude() != null && gpTest.getLongitude() != null) {
            // Generowanie XML z polozenia geograficznego.
            XStream gpXstream = new XStream(new DomDriver());
            gpXstream.alias("geoPoint", GeoPoint.class);
            String gpXML = gpXstream.toXML(gpTest);

            contextStoreBean.setMSG("Wyslano zapytanie testowe:\n\n" + addressXML + "\n\nOdebrano odpowiedz:\n\n" + gpXML + "\n\n");
            return SUCCESS;
        }
        else {
            contextStoreBean.setMSG("Wyslano zapytanie testowe:\n\n" + addressXML + "\n\nBrak odpowiedzi!\n\n");
            return ERROR;
        }
    }
}
